<?php

namespace app\data\controller\record;

use app\admin\service\WxWorkService;
use app\data\service\CityUserRelationService;
use app\data\service\RecordService;
use app\data\service\StringParse;
use think\admin\Controller;
use think\admin\service\AdminService;
use think\facade\Cache;

/**
 * 城市施工者采集
 * Class CarRecordCityOwner
 * @package app\data\controller\user
 */
class CarRecordCityOwner extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'data_record';

    /**
     * 城市施工者采集
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $ts['ta'] = ['vip' => '', 'name' => '全部记录', 'count' => 0];
        $this->total = $ts;

        // 设置页面标题
        $this->title = '城市施工者采集';
        // 创建查询对象
        $query = $this->_query($this->table)->order('id desc');

        if (!AdminService::instance()->isSuper()) {
            $query->where('uuid_city', AdminService::instance()->getUserId());
        } else {
            $uuidCityName = $this->request->request('uuid_city_name', '');
            if (!empty($uuidCityName)) {
                $uuidCityIds = $this->app->db->name('work_user')->where('name', 'like', "%{$uuidCityName}%")->column('id');
                $query->whereIn('uuid_city', $uuidCityIds);
            }
        }

        $uuidDockingName = $this->request->request('uuid_docking_name', '');
        if (!empty($uuidDockingName)) {
            $uuidDockingIds = $this->app->db->name('work_user')->where('name', 'like', "%{$uuidDockingName}%")->column('id');
            $query->whereIn('uuid_docking', $uuidDockingIds);
        }

        $result = $query->like('phone,username,plate_number')->equal('id,province#query_province,query_city#city,query_area#area,paint_status,end_paint_status,fail_status,is_deal')->dateBetween('time_docking,time_complete');

        // 列表选项卡
        $this->type = trim(input('type', 'ta'), 't');
        if ($this->type === '1') {
            $query->whereIn('paint_status', [-1, 0])->whereNull('time_invite');
        } else if ($this->type === '2') {
            $query->whereIn('paint_status', [-1, 0]);
        }

        // 数据查询分页
        if (input('output') == 'json') {
            $result = $result->page(true, false);
            $this->success('', $result);
        } else {
            $result->page();
        }
    }

    /**
     * 城市施工者采集导出
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function indexExport()
    {
        $this->index();
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _indexExport_page_filter(array &$data)
    {
        $this->_page_filter($data);
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _page_filter(array &$data)
    {
        RecordService::instance()->format($data);

        $ids = array_column($data, 'id');
        $recordRemarkLogs = $this->app->db->name('data_record_remark_log')->whereIn('record_id', $ids)->order('id', 'desc')->select()->toArray();
        foreach ($recordRemarkLogs as $recordRemarkLog) {
            if (empty($id2reason[$recordRemarkLog['record_id']])) {
                $id2reason[$recordRemarkLog['record_id']] = $recordRemarkLog['remark'];

                if (!empty($recordRemarkLog['remind_at']) && date('Y-m-d', strtotime($recordRemarkLog['remind_at'])) == date('Y-m-d')) {
                    $showRed[$recordRemarkLog['record_id']] = 1;
                }
            }
        }

        foreach ($data as &$item) {
            if (is_string($item['time_invites'])) {
                $item['time_invites'] = explode("\n", $item['time_invites']);
                foreach ($item['time_invites'] as $key => $time) {
                    if (empty($time)) {
                        unset($item['time_invites'][$key]);
                    }
                }
            } else {
                $item['time_invites'] = [];
            }

            $item['analyze_reason_text'] = RecordService::instance()->analyzeReasons($item['analyze_reason']) ?: '暂无';
            $item['remark'] = $id2reason[$item['id']] ?? '暂无';
            $item['remark_show_red'] = $showRed[$item['id']] ?? 0;
        }
    }

    /**
     * 表单结果处理
     * @param boolean $state
     */
    protected function _form_result(bool $state, array $data)
    {
        if ($state) {
            $this->success('保存成功！');
        }
    }

    /**
     * 数据列表处理
     * @param array $data
     */
    protected function _teams_page_filter(array &$data)
    {
    }

    /**
     * 编辑
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if ($this->isMobile()) {
            $template = 'form_mobile';
        } else {
            $template = 'form';
            if (!empty($showId = request()->get('show_id', 0))) {
                return redirect(getHttpHost() . "/admin.html#/data/record.car_record_city_owner/index.html?show_id={$showId}");
            }
        }
        $this->_form($this->table, $template);
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        $this->title = '信息采集管理';
        if ($this->request->isPost()) {
            // 检查登录账号是否出现重复
            $record = $this->app->db->name('data_record')->where('id', $data['id'])->findOrEmpty();
            if (!empty($data['phone'])) {
                $where = ['phone' => $data['phone']];
//                if ($this->app->db->name($this->table)->whereNotIn('id', [$data['id']])->where($where)->count() > 0) {
//                    $this->error("手机号已经存在，请使用其它手机号！");
//                }
            }

            [$digits, $chinese] = StringParse::instance()->splitDigitsAndChinese($data['car_vehicle_type']);
            $carVehicleTypeId = StringParse::instance()->carVehicleType($digits, $chinese);
            if (!empty($carVehicleTypeId)) {
                $data['car_vehicle_type_id'] = $carVehicleTypeId;
            }

            if (empty($data['time_invite'])) {
                unset($data['time_invite']);
            }
            if (empty($data['time_plan'])) {
                unset($data['time_plan']);
            }
            if (empty($data['time_docking'])) {
                unset($data['time_docking']);
            }
            if (empty($data['time_complete'])) {
                unset($data['time_complete']);
            }

            if ($data['paint_status'] == 1) {
                if (empty($data['painter'])) {
                    $this->error('喷漆师傅不能为空');
                }
                if (in_array($record['paint_status'], [-1, 0])) {
                    $data['time_complete'] = date('Y-m-d H:i:s');
                } else {
                    $data['time_complete'] = null;
                }
                $data = CityUserRelationService::instance()->calcPaintPrice($record, $data);
            }

            if (!empty($data['invite_remark']) && empty($data['time_invite']) && empty($record['time_invite'])) {
                $data['time_invite'] = date('Y-m-d H:i:s');
            }
            if (!empty($record['time_invite'])) {
                unset($data['time_invite']);
            }

//            $cacheKey = config('cacheKey.uid2user') . $data['id'];
//            Cache::delete($cacheKey);
        } else {
            $data = RecordService::instance()->formatOne($data);
        }
    }

    /**
     * 删除
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->app->db->name($this->table)->where('id', input('id'))->delete();
        $cacheKey = config('cacheKey.uid2user') . input('id');
        Cache::delete($cacheKey);
        $this->success('删除成功');
    }
}